package com.ssl.sslliving.commodity.service.impl;

import com.ssl.sslliving.commodity.entity.AttrEntity;
import com.ssl.sslliving.commodity.service.AttrService;
import com.ssl.sslliving.commodity.vo.AttrGroupWithAttrsVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssl.common.utils.PageUtils;
import com.ssl.common.utils.Query;

import com.ssl.sslliving.commodity.dao.AttrgroupDao;
import com.ssl.sslliving.commodity.entity.AttrgroupEntity;
import com.ssl.sslliving.commodity.service.AttrgroupService;

import javax.annotation.Resource;


@Service("attrgroupService")
public class AttrgroupServiceImpl extends ServiceImpl<AttrgroupDao, AttrgroupEntity> implements AttrgroupService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrgroupEntity> page = this.page(
                new Query<AttrgroupEntity>().getPage(params),
                new QueryWrapper<AttrgroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long categoryId) {
        String key = (String) params.get("key");
        QueryWrapper<AttrgroupEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(key)) {
            //wrapper.eq("id", key).or().like("name", key);
            wrapper.and((obj) -> {
                obj.eq("id", key).or().like("name", key);
            });
        }
        if (categoryId != 0) {
            wrapper.eq("category_id", categoryId);
        }
        IPage<AttrgroupEntity> page = this.page(
                new Query<AttrgroupEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Resource
    private AttrService attrService;

    @Override
    public List<AttrGroupWithAttrsVo> getAttrGroupWithAttrsByCategoryId(Long categoryId) {
        List<AttrgroupEntity> attrgroupEntities =
                this.list(new QueryWrapper<AttrgroupEntity>().eq("category_id", categoryId));
        List<AttrGroupWithAttrsVo> attrGroupWithAttrsVos = attrgroupEntities.stream().map(attrgroupEntity -> {
            AttrGroupWithAttrsVo attrGroupWithAttrsVo = new AttrGroupWithAttrsVo();
            BeanUtils.copyProperties(attrgroupEntity, attrGroupWithAttrsVo);
            List<AttrEntity> attrEntities = attrService.getRelationAttr(attrGroupWithAttrsVo.getId());
            attrGroupWithAttrsVo.setAttrs(attrEntities);
            return attrGroupWithAttrsVo;
        }).collect(Collectors.toList());
        return attrGroupWithAttrsVos;
    }

}